
$(function(){
    $(".phone-enter").bind("input porpertychange", function(){
        if ($(this).val().length == 11){
            $(".receive-btn").addClass("active");
        }else{
            $(".receive-btn").removeClass("active");
        }
    });
    if($.cookie("captcha")){
        var count = $.cookie("captcha");
        var btn = $('#getting');
        btn.text(count+'秒后可获取').attr('disabled',true).css('cursor','not-allowed');
        var resend = setInterval(function(){
            count--;
            if (count > 0){
                $(".botain-btn").addClass("btn-invalid");
                btn.text(count+'秒后可获取').attr('disabled',true).css('cursor','not-allowed');
                $.cookie("captcha", count, {path: '/', expires: (1/86400)*count});
            }else {
                $(".botain-btn").removeClass("btn-invalid");
                clearInterval(resend);
                btn.text("获取验证码").removeClass('disabled').removeAttr('disabled style');
            }
        }, 1000);
    }
    $("#getting").click(function(){
        var phone = $(".phone-enter").val();
        $.ajax({
            type: "post",
            url: "http://51son.net:8088/api/member/sendSmsCode",
            data:{
                mobile: phone,
                type: 1
            },
            success:function(result){
                if (result.success){
                    var btn = $("#getting")
                    var count = 60;
                    var resend = setInterval(function(){
                        count--;
                        if (count > 0){
                            $(".botain-btn").addClass("btn-invalid");
                            btn.text(count+"秒后可获取");
                            $.cookie("captcha", count, {path: '/', expires: (1/86400)*count});
                        }else {
                            $(".botain-btn").removeClass("btn-invalid");
                            clearInterval(resend);
                            btn.text("获取验证码").removeAttr('disabled style');
                        }
                    }, 1000);
                    btn.attr('disabled',true).css('cursor','not-allowed');
                }else{
                    layer.msg(result.message);
                }
            },
            error:function(){
                layer.msg('网络连接异常，请稍后再试');
            }
        });
    });
});

// 
// 


!function(win, lib) {
    var timer,
        doc     = win.document,
        docElem = doc.documentElement,

        vpMeta   = doc.querySelector('meta[name="viewport"]'),
        flexMeta = doc.querySelector('meta[name="flexible"]'),
 
        dpr   = 0,
        scale = 0,
 
        flexible = lib.flexible || (lib.flexible = {});
 
    // 设置了 viewport meta
    if (vpMeta) {
 
        
        var initial = vpMeta.getAttribute("content").match(/initial\-scale=([\d\.]+)/);
 
        if (initial) {
            scale = parseFloat(initial[1]); 
            dpr = parseInt(1 / scale);      
        }
 
    }
    // 设置了 flexible Meta
    else if (flexMeta) {
        var flexMetaContent = flexMeta.getAttribute("content");
        if (flexMetaContent) {
 
            var initial = flexMetaContent.match(/initial\-dpr=([\d\.]+)/),
                maximum = flexMetaContent.match(/maximum\-dpr=([\d\.]+)/);
 
            if (initial) {
                dpr = parseFloat(initial[1]);
                scale = parseFloat((1 / dpr).toFixed(2));
            }
 
            if (maximum) {
                dpr = parseFloat(maximum[1]);
                scale = parseFloat((1 / dpr).toFixed(2));
            }
        }
    }
 
    // viewport 或 flexible
    // meta 均未设置
    if (!dpr && !scale) {
        // QST
        // 这里的 第一句有什么用 ?
        // 和 Android 有毛关系 ?
        var u = (win.navigator.appVersion.match(/android/gi), win.navigator.appVersion.match(/iphone/gi)),
            _dpr = win.devicePixelRatio;
 
        // 所以这里似乎是将所有 Android 设备都设置为 1 了
        dpr = u ? ( (_dpr >= 3 && (!dpr || dpr >= 3))
                        ? 3
                        : (_dpr >= 2 && (!dpr || dpr >= 2))
                            ? 2
                            : 1
                  )
                : 1;
 
        scale = 1 / dpr;
    }
 
    docElem.setAttribute("data-dpr", dpr);
 
    // 插入 viewport meta
    if (!vpMeta) {
        vpMeta = doc.createElement("meta");
         
        vpMeta.setAttribute("name", "viewport");
        vpMeta.setAttribute("content",
            "initial-scale=" + scale + ", maximum-scale=" + scale + ", minimum-scale=" + scale + ", user-scalable=no");
 
        if (docElem.firstElementChild) {
            docElem.firstElementChild.appendChild(vpMeta)
        } else {
            var div = doc.createElement("div");
            div.appendChild(vpMeta);
            doc.write(div.innerHTML);
        }
    }
 
    function setFontSize() {
        var winWidth = docElem.getBoundingClientRect().width;
 
        if (winWidth / dpr > 540) {
            (winWidth = 540 * dpr);
        }
 
        // 根节点 fontSize 根据宽度决定
        var baseSize = winWidth / 10;
 
        docElem.style.fontSize = baseSize + "px";
        flexible.rem = win.rem = baseSize;
    }
 
    // 调整窗口时重置
    win.addEventListener("resize", function() {
        clearTimeout(timer);
        timer = setTimeout(setFontSize, 300);
    }, false);
 
     
    // 这一段是我自己加的
    // orientationchange 时也需要重算下吧
    win.addEventListener("orientationchange", function() {
        clearTimeout(timer);
        timer = setTimeout(setFontSize, 300);
    }, false);
 
 
    // pageshow
    // keyword: 倒退 缓存相关
    win.addEventListener("pageshow", function(e) {
        if (e.persisted) {
            clearTimeout(timer);
            timer = setTimeout(setFontSize, 300);
        }
    }, false);
 
    // 设置基准字体
    if ("complete" === doc.readyState) {
        doc.body.style.fontSize = 12 * dpr + "px";
    } else {
        doc.addEventListener("DOMContentLoaded", function() {
            doc.body.style.fontSize = 12 * dpr + "px";
        }, false);
    }
  
    setFontSize();
 
    flexible.dpr = win.dpr = dpr;
 
    flexible.refreshRem = setFontSize;
 
    flexible.rem2px = function(d) {
        var c = parseFloat(d) * this.rem;
        if ("string" == typeof d && d.match(/rem$/)) {
            c += "px";
        }
        return c;
    };
 
    flexible.px2rem = function(d) {
        var c = parseFloat(d) / this.rem;
         
        if ("string" == typeof d && d.match(/px$/)) {
            c += "rem";
        }
        return c;
    }
}(window, window.lib || (window.lib = {}));


window.onload = function(){

    var restStu = false;
    var nextStu = false;
    var host = window.location.host == 'fe.office.bzdev.net' ? 'fe.office.bzdev.net/source/csf' :  window.location.host ;
    var hostLast = !!window.location.host.split('.')[3] ? '.'+window.location.host.split('.')[3] : '';
    var urlHost = window.location.host.split('.')[1]+'.'+window.location.host.split('.')[2]+hostLast;
    var UrlFrom = '';
    var url = window.location.href;
    var shareURL = window.location.href;
    var href = location.hash;
    var wh = $(window).height();
    var ww = $(window).width();
    var recordNum = 0;
    var isLogin = true;


    // 分享
    var share = function(){  
        var url=window.location.href.split('#')[0];
        var shareTitle = '美国亚利桑那生殖医学中心指导出题《试管婴儿测试》';
        var shareDesc = '认真回答，真的很准！';
        var shareImg = 'http://www.51son.net/images/web/tools/330.png';
        $.ajax({
            url: "http://51son.net/wx/shareSign",
            data:{
                url: url
            },
            type: "POST",
            async: false,
            dataType: "json",
            success: function(data){
                wx.config({
                  debug: false,
                  appId: 'wx8e3b66d722abd919',
                  timestamp:data.timestamp,
                  nonceStr:data.nonceStr,
                  signature:data.signature,
                  jsApiList: [
                      'checkJsApi',
                      'onMenuShareTimeline',
                      'hideOptionMenu',
                      'onMenuShareAppMessage',
                      'onMenuShareQQ'
                  ]
              });
              
              wx.ready(function(){
                 //wx.hideOptionMenu();/***隐藏分享菜单****/
                 wx.checkJsApi({
                  jsApiList: [
                    'getLocation',
                    'onMenuShareTimeline',
                    'onMenuShareAppMessage',
                    'onMenuShareQQ'
                  ],
                  success: function (res) {
                    //alert(res.errMsg);
                  }
                });
                   
                wx.onMenuShareAppMessage({
                      title: shareTitle,
                      desc: shareDesc,
                      link: url,
                      imgUrl: shareImg,
                      trigger: function (res) {
                        //alert('用户点击发送给朋友');
                      },
                      success: function (res) {
                        
                      },
                      cancel: function (res) {
                        //alert('已取消');  
                      },
                      fail: function (res) {
                        alert(res.errMsg);
                      }
                   });
                  
                  // 2.2 监听“分享到朋友圈”按钮点击、自定义分享内容及分享结果接口  
                  wx.onMenuShareTimeline({
                      title: shareTitle,
                      desc: shareDesc,
                      link: url,
                      imgUrl: shareImg,
                      trigger: function (res) {
                        //alert('用户点击分享到朋友圈');
                      },
                      success: function (res) {
                        
                      },
                      cancel: function (res) {
                        //alert('已取消');  
                      },
                      fail: function (res) {
                        alert(res.errMsg);
                      }  
                });
                wx.onMenuShareQQ({
                    title: shareTitle, // 分享标题
                    desc: shareDesc, // 分享描述
                    link: url, // 分享链接
                    imgUrl: shareImg, // 分享图标
                    success: function (res) { 
                       // 用户确认分享后执行的回调函数
                    },
                    cancel: function (res) { 
                       // 用户取消分享后执行的回调函数
                    }
                });
                   
                wx.error(function (res) {
                       alert(res.errMsg);
                 });
               }); 
            },
            error: function() {
                alert('ajax request failed!');
                return;
            }
        });
      };



    //获取URL参数
    var getName = function (name) {
      name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
      var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
      results = regex.exec(location.search);
      return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
     };


    //进入下一页判断

    var nextPage = function(ele,jump){
        var jump = !!jump ? jump : 0;
        var page = parseInt(ele.closest(".page").attr("data-page").replace('profile',''))+1+jump;
        if(nextStu == true){
            ele.closest(".page").find(".page-bot").children("a").removeClass("btn-gray").addClass("btn-red").attr("href","#profile"+page);
            ele.closest(".page").find(".others-bot").children("a").removeClass("btn-gray").addClass("btn-red");
            $('.page-bot .btn-red').not('#go').off('click').on('click',function(e){
              e.preventDefault();
              var page = $(this).attr('href'); //parseInt($(this).closest(".page").attr("data-page").replace('profile',''))+1+jump;
              window.location.href = '//'+host+'/webRoot/Html5/tools.html'+UrlFrom+page;
            if(restStu == true){
                $(this).closest(".page").next('.page').find(".page-bot").children("a").not('#go').off('click');
            }
            });
        }else{
            ele.closest(".page").find(".page-bot").children("a").addClass("btn-gray").removeClass("btn-red").attr("href","javascript:;");
             $('.page-bot .btn-gray').not('#go').off('click').on('click',function(){
                return false;
             })
        }   
    };

    $('.cover .enter').click(function(e){
        e.preventDefault();
        window.location.href = '//'+host+'/webRoot/Html5/tools.html'+UrlFrom+'#profile1';
    });


    //清除答题选项
    var clearFun = function(){
        $('.page-bot .btn-gray').not('#go').off('click');
            $('div[data-page="profile1"]').find('input[type="hidden"]').val('30##150##50');
            $('div[data-page="profile1"]').find(".ruler").eq(0).find(".main").attr('value','600').css('-webkit-transform','translateX(-600px)');
            $('div[data-page="profile1"]').find(".row").eq(0).find(".number").text('30');
            $('div[data-page="profile1"]').find(".ruler").eq(1).find(".main").attr('value','104').css('-webkit-transform','translateX(-104px)');
            $('div[data-page="profile1"]').find(".row").eq(1).find(".number").text('150');
            $('div[data-page="profile1"]').find(".ruler").eq(2).find(".main").attr('value','416').css('-webkit-transform','translateX(-416px)');
            $('div[data-page="profile1"]').find(".row").eq(2).find(".number").text('50');

            $('.tag .active').each(function(){
                $(this).removeClass("active");
            });

            $('.page:not([data-page="profile1"])').find('.page-bot').children("a").addClass("btn-gray").removeClass("btn-red").attr('href','javascript:;');
            $('.other-input,.tips-info').hide();

            $('.page[data-page="profile9"]').find('.selectize').eq(3).find("li").click();

            $('.page[data-page="profile7"],.page[data-page="profile8"]').find(".select-box").each(function(){
                $(this).find('.val').text('请选择');
                $(this).find("li").removeClass("selected");
            });

            $('[data-page="profile9"]').find(".row-box").addClass("row-hide");

            $('.page[data-page="profile9"]').find('.wish').each(function(){
                $(this).find('.val').text('请选择');
                $(this).find("li").removeClass("selected");
            });
    };

    //重测
    $('.icon-rest,.icon-edit').click(function(){
        var html = '';
        var btnTxt = '';
        var className = '';
        if($(this).hasClass("icon-rest")){
            html = '<p>重新测试将会覆盖现有的数据</p>';
            btnTxt = '确认重测';
            $('.rest-box .box-bot .rest-enter').addClass("rest-start");
        }else{
            html = '<p>重新编辑将会覆盖现有的数据</p>'
            btnTxt = '确认编辑';
            $('.rest-box .box-bot .rest-enter').removeClass("rest-start");      
        };

        $('.rest-box .main').html(html);
        $('.rest-box .box-bot .rest-enter').text(btnTxt);

        $('.rest-box').addClass("rest-box-show").attr("style", "display:block;");
        if($('.overlayout').length ==0){
            $('body').append("<div class='overlayout'></div>")
        };

        $('.rest-start').on('click',function(e){
            e.preventDefault();
            restStu= true;

            clearFun();
            window.location.href = '//'+host+'/webRoot/Html5/tools.html'+UrlFrom+'#profile1';
            //usernameFun();
        });
    });

    $('.rest-box .rest-close').click(function(){
        $('.rest-box').removeClass("rest-box-show");
        $('.overlayout').remove();
    });
    $('.rest-enter').click(function(){
        $('.rest-box').removeClass("rest-box-show");
        $('.overlayout').remove();      
    });


    var hash = function(){
        var hash =window.location.hash;
        var url = window.location.href;
        recordNum++;
        recordUrl = hash;
        if (recordUrl == '' && recordNum > 1) {
            if (isCrazy) {
                window.location.href = '//'+host+'/webRoot/Html5/tools.html'+UrlFrom+'#profile1';
            }
        };

        hashName =hash.replace("#","").replace('?','&').split('&')[0];
         if(hashName.replace("profile","") != '' && hashName.replace("profile","")<=9){
            $('form.answer').show();
          }else{
            $('form.answer').hide();
            if (!hashName) {
                $('.cover').show();
            }
          };

        if(hashName){
            $('.cover').hide();
            $(".page").hide();
            $(".page[data-page='"+hashName+"']").show();

        }else if(hashName == ''){
            $(".page,.share-page").hide();
            $(".page").addClass("page-enter")
            $(".page[data-page='cover']").show();
        };

        if(hashName == 'cover'){
            $(".page").hide();
            $(".cover").show();
            $(".page").addClass("page-enter");
            $(".download-box").removeAttr("style");
        };
       
        if(hashName == 'profile10'){
            $('.rest-box').show();
            $(".download-box").removeAttr("style");
        };
        if(hashName == 'profile11'){
            $(".download-box").removeAttr("style");
        };
        if(hashName == 'profile12'){
            $('.rest-box').show();
        };
        if(hashName == 'profile13'){
            
            var day = getQueryStringRegExp('day').split('-');
            var cost = getQueryStringRegExp('cost').split('-');
            var lrh = getQueryStringRegExp('lrh').replace('#profile13','');

            $('.share-page .info dl').eq(1).find(".cost").eq(0).text(cost[0]/10000);
            $('.share-page .info dl').eq(1).find(".cost").eq(1).text(cost[1]/10000);
            $('.share-page .info dl').eq(0).find(".num").eq(0).text(day[0]);
            $('.share-page .info dl').eq(0).find(".num").eq(1).text(day[1]);                
            $('.share-page .data .num').attr('data-num',getQueryStringRegExp('success'));

            $('.share-page .ivf').text(ivfStr[getQueryStringRegExp('ivf')]);
            $('.share-page .lrh').text(decodeURIComponent(getQueryStringRegExp('lrh').split('#')[0]));
            setTimeout(function(){
                probability();
             },100)

        };
        if(hashName == 'profile1' || hashName == 'profile2' || hashName == 'profile3' || hashName == 'profile4' || hashName == 'profile5' || hashName == 'profile6' || hashName == 'profile7' || hashName == 'profile8' || hashName == 'profile9'){
            $(".download-box").attr("style", "display:block;");
        }
        $(window).scrollTop('0');
        $('.tool').removeClass("tool-open");
    
    };
    hash();

    window.addEventListener("hashchange", hash, false);
    if (!getName('from')) {
        if(hashName.replace("profile","") == ''){
            userStu = true
            
        }else if(hashName.replace("profile","")<= 9 && hashName.replace("profile","")>0 ){
                window.location.hash = !!localStorage.getItem('success_rate') ? '#profile11' : '#cover';
        }else if(hashName.replace("profile","") ==11){
            window.location.href = '//'+host+'/webRoot/Html5/tools.html'+UrlFrom;
            $('div[page-main="item1"]').show();
        }else if(hashName.replace("profile","") ==12){
            if(!isLogin){
                window.location.href = '//'+host+'/webRoot/Html5/tools.html'+UrlFrom;
            }
        }else if(hashName.replace("profile","") ==10){
            if(!isLogin){
                window.location.href = '//'+host+'/webRoot/Html5/tools.html'+UrlFrom;
            }else{
                window.location.href = '//'+host+'/webRoot/Html5/tools.html'+UrlFrom;
                $('div[page-main="item1"]').show();
            }
        }
    };

    //选择下拉框
    var sbh = $('.selectize .bot').height();
    $('.selectize .option ul').css("max-height",wh-sbh-30+"px");
    $('.selectize .val').click(function(e){
        e.stopPropagation();
        if($('.overlayout').length ==0){
            $('body').append("<div class='overlayout'></div>")
        }
        $(this).parent(".selectize").find('.option').addClass("show-option");

        $(this).siblings(".option").show();
            $('.overlayout').on('click',function(){
                $(this).remove();
                $('.selectize .option').removeClass("show-option");
        });
    });

    $('.selectize .close').click(function(){
        $(this).closest(".option").removeClass("show-option");
        $('.overlayout').remove();

    });

    $('.selectize .option li').click(function(){
        var size = $(this).closest(".page").find(".selectize").size();
        var ele  = $(this).closest(".page").find(".selectize");
        var $this = $(this);
        var n =0;
        $(this).addClass("selected").siblings("li").removeClass("selected");
        $(this).closest(".selectize").find(".val").text($(this).text()).siblings(".option").removeClass("show-option");
        $('.overlayout').remove();
        if($(this).closest(".selectize").hasClass("wish")){
            if($(this).hasClass("has")){
                $(".row-box").removeClass("row-hide");
                $(this).attr('data-aa','false');
                checkFun($this);
            }else{
                $(".row-box").addClass("row-hide");
                $(this).attr('data-aa','true')
            }
        }
        if($(this).closest(".page").hasClass("profile")){
            var t = $(this).attr('data-key');
            setTimeout(function(){
                $(this).closest(".selectize").siblings("input[type='hidden']").val(t)
            },200)
        }
        $(this).removeClass("hover");
    });

    var checkFun = function($this){
        var ele  = $this.closest(".page").find(".select-box");
        var n =0;
        var size = $this.closest(".page").find('.row:not(".row-hide")').find(".select-box").size();

        $this.closest(".page").find('.row:not(".row-hide")').find(".select-box").each(function(){
            var v =$(this).find('.val').text();
            if(ele.hasClass("selectize-buret")){
                if(v != '0'){
                    n=0
                }else{
                    n=1;
                    localStorage.removeItem('eighth_screen');
                    $('input[name="eighth_screen"]').val("");
                }
            }
            if(v == '请选择'){
                nextStu = false;
                return false;
            }else{
                nextStu = true;
            }
        })
        nextPage($this,n)
        
    };
    $('.select-box .option li').click(function(){
        var ele  = $(this).closest(".page").find(".select-box");
        var n =0;
        var $this = $(this);
        var arr = new Array();
        var arr2 = new Array(),arr3='';
        var txt2 ='';
        $(this).addClass("selected").siblings("li").removeClass("selected");
            ele.each(function(index){               
                    txt2 = '';
                    if(!$(this).closest(".row").hasClass("row-hide") && !$(this).closest(".row").hasClass("row-actitity")){
                        var s = $(this).find(".selected").size();
                        var txt  =$(this).find(".selected").attr('data-key',function(i,v){                          
                            var t = $(this).closest(".select-box").hasClass("chosen") ? $(this).text()+'-' : '';
                            txt2 +=  (i > 0 ? "," : "") +t+v;
                        });
                        arr.push(txt2);
                }
            });
        var arrayJoin = arr.join("##");
        $(this).closest(".page").find("input[type='hidden']").val(arrayJoin);
        checkFun($this);
    });

    //多级选择
    var h33 = wh/3;
    $('.chosen .option').css('max-height',h33*2+"px");
    $('.chosen .option .list,.chosen .option .sub-list').css("max-height",(h33*2)-40+"px");

    $('.chosen .val').click(function(){
        var v = $(this).text();
        if(v == '请选择'){
            $(this).siblings(".option").find('.sub-list').hide();
            $(this).siblings('.option').find(".tit").text('请选择区域');
        }else{
            $(this).siblings('.option').find(".tit").text($(this).text());
        }

        if($('.overlayout').length ==0){
            $('body').append("<div class='overlayout'></div>")
        }
        $(this).siblings(".option").show();
        $('.overlayout').on('click',function(){
                $(this).remove();
                $('.chosen .option').hide();
        });
    });

    //遮罩层
    $('.overlayout').on('click',function(){
        $(this).hide();
        $('.selectize').removeClass("show-option");
        $('.chosen .option').hide();
    });

    //单选
    $('.icon-radio').click(function(){
        $(this).addClass("radio-selected").siblings().removeClass("radio-selected");
        costFun();
        costStartFun();
    });

    //多选
    
    $('.tag span').click(function(){
        var arr = new Array();
        var hasActive = false;
        var parentTxt = $(this).closest(".page").find("input[type='hidden']").val();

            if($(this).hasClass("active")){
                $(this).removeClass("active");
                nextStu = false;
                if($(this).hasClass("other")){
                    $(this).siblings(".other-input").hide();
                }
                if($(this).hasClass("show-tips")){
                    $(this).siblings(".tips-info").hide();
                }
            }else{
                $(this).addClass("active");
                if($(this).hasClass("normal")){
                    $(this).addClass("active").siblings("span").removeClass("active");
                    $(this).siblings(".other-input").hide();

                }else{
                    $(this).addClass("active").siblings(".normal").removeClass("active");
                }
                if($(this).hasClass("other")){
                    $(this).siblings(".other-input").show();//.find("input").focus();
                }
                if($(this).hasClass("show-tips")){
                    $(this).siblings(".tips-info").show();
                }
            }

        $(this).closest(".tag").find(".active").each(function(){

            var txt = $(this).attr('data-key');

            arr.push(txt)
            
            nextStu = true;
            hasActive = true;
        }); 

        if($(this).siblings(".other-input").css('display') == 'block' && $(this).siblings(".other-input").find('textarea').val() != ''){
            var v = $(this).siblings(".other-input").find('textarea').val();
            var vTxt =  $(this).closest(".page").find('.other').attr('data-key');
            if(hasActive == true){
                arr  = arr.join(',');
                arr = arr.replace('0','');

                $(this).closest(".page").find("input[type='hidden']").val(arr+vTxt+'.'+v);

            }else{
                $(this).closest(".page").find("input[type='hidden']").val(vTxt+'.'+v);
            }   
        }else{
            $(this).closest(".page").find("input[type='hidden']").val(arr);
        }
        
        nextPage($(this));
    });

    $('.other-input').find('textarea').blur(function(){        
        var parentTxt = $(this).closest(".page").find("input[type='hidden']").val();
        var vTxt =  $(this).closest(".page").find('.other').attr('data-key');
        var v = $(this).val().replace(/\s+/g,'');
        var txt = $(this).val();
        var m = parentTxt.split('.');
        if(v != ''){
            if(parentTxt != ''){
            
                if(m.length <= 1){
                    if(parentTxt == ''){
                        parentTxt = parentTxt.replace('0','');
                        $(this).closest(".page").find("input[type='hidden']").val(vTxt+'.'+txt);
                    }else{
                        parentTxt = parentTxt.replace(',0','');
                        $(this).closest(".page").find("input[type='hidden']").val(parentTxt+','+vTxt+'.'+txt);
                    }
                    
                }else{
                     parentTxt = parentTxt.replace('0.'+m[1],'');
                     if(parentTxt == ''){
                        $(this).closest(".page").find("input[type='hidden']").val(vTxt+'.'+txt);
                     }else{
                        $(this).closest(".page").find("input[type='hidden']").val(vTxt+'.'+txt);
                     }
                     
                }
            }else{  
                $(this).closest(".page").find("input[type='hidden']").val(vTxt+'.'+txt);
            }

        }else{
            parentTxt = parentTxt.replace('.'+m[1],'');
            if($(this).closest(".page").find(".other").hasClass("active")){
                $(this).closest(".page").find("input[type='hidden']").val(parentTxt);
            }else{
                $(this).closest(".page").find("input[type='hidden']").val(parentTxt);
            }
        }
    });

    var cityClick=function(){
        $('.chosen .sub-list li').on('click',function(){
            var t = $(this).closest('.option-main').find(".list").find(".selected").text();
            var attr2 = $(this).attr('data-key');
            var ele  = $(this).closest(".page").find(".select-box");
            var arr = new Array();
            var arr2 = new Array(),arr3='';
            var txt2 ='';

            $(this).closest('.option-main').siblings(".tit").text(t + " "+$(this).text());
            $(this).addClass("selected").siblings("").removeClass("selected");
            $(this).closest('.chosen').find('.val').text(t +$(this).text());
            $(this).closest('.chosen').find('.val').attr('data-key',attr2)
            $(this).closest('.chosen').find('.option').hide();

            if($(this).closest(".chosen").hasClass("province")){
                var sibling = $(this).closest(".row").siblings(".row").find(".chosen");
                sibling.find(".sub-list").find("li[data-key='"+attr2+"']").addClass("selected");
                sibling.find('.val').attr('data-key',attr2).text(t +$(this).text());

                $(this).closest(".chosen").removeClass("province");
            }else{
                $(this).closest(".row").siblings(".row").find(".chosen").removeClass("province");
            }
            $('.overlayout').remove();      
            $(this).addClass("selected").siblings("li").removeClass("selected");
            ele.each(function(index){               
                    txt2 = '';
                    if(!$(this).closest(".row").hasClass("row-hide")){
                        var s = $(this).find(".selected").size();
                        var txt  =$(this).find(".selected").attr('data-key',function(i,v){                          
                            var t = $(this).closest(".select-box").hasClass("chosen") ? $(this).text()+'-' : '';
                            txt2 +=  (i > 0 ? "," : "") +t+v;
                        });
                        arr.push(txt2);
                }
            });
            var arrayJoin = arr.join("##");
            $(this).closest(".page").find("input[type='hidden']").val(arrayJoin);
            checkFun($(this));
        });
    };

    //拖动
    setTimeout(function(){

        var n =0;

        var u,end,start,g,g2;

        var w0 = 50;

        var w1 = 10.4;

        var w2=52;

        var heightVal =$("div[data-page='profile1']").find(".row").eq(1).find(".number").attr("initial-value"); //150-140

        var widthVal =$("div[data-page='profile1']").find(".row").eq(2).find(".number").attr("initial-value"); //550-300 /2.5 /10 保留最后一们小数

        var ageVal = $("div[data-page='profile1']").find(".row").eq(0).find(".number").attr("initial-value"); //30-18



        $('.ruler .main').eq(0).css({
            '-webkit-transform':'translateX(-'+Math.ceil(parseInt(ageVal*w0))+'px)'
        }).attr('value',Math.ceil(ageVal*w0));

        $('.ruler .main').eq(1).css({
            '-webkit-transform':'translateX(-'+parseInt(heightVal*w1)+'px)'
        }).attr('value',heightVal*w1);
        
        $('.ruler .main').eq(2).css({
            '-webkit-transform':'translateX(-'+parseInt(widthVal*w2)+'px)'
        }).attr('value',widthVal*w2);



        for( var i =0 ; i < $('.ruler').length; i++){
            var liW = $('.ruler').eq(i).find("li").width();
            var size =  $('.ruler').eq(i).find('li').size();
        }

        $('body').on('touchcancel,touchend,touchmove,touchstart',function(e){
             e.preventDefault();
        })

        $('.selectize li').on('touchstart',function(){
            $(this).addClass("hover").siblings("li").removeClass("hover");
        })

        $('.selectize li').on('touchsend',function(){
            $(this).removeClass("hover");
        })


        $('.ruler ul').on("touchstart",function(e){
            var  initial = $(this).attr('data-initial');
            e.stopPropagation();
             v = parseInt($(this).parent(".main").attr('value'));

            if($(this).closest('.ruler').hasClass("ruler-weight")){
                start = 0;
                end = '-1458';
                 g = 52;
            }else if($(this).closest('.ruler').hasClass("ruler-age")){
                start = 0;
                end = '-1600';
                 g = 50;

            }else{
                start = 0;
                end = '-623';
                g = 10.4;
            }   


            if(initial == 'true'){
                startX = e.originalEvent.changedTouches[0].pageX+v;
                $(this).attr('data-initial','false');
            }else{
                startX = e.originalEvent.changedTouches[0].pageX-v;
            }
        });



        $('.ruler ul').on("touchmove",function(e){

            var number = parseInt($(this).closest(".row").find('.number').attr('value'));   

            moveX = e.originalEvent.changedTouches[0].pageX;    

            X = moveX - startX;
            
            if(X>0){
                var vv = $(this).parent(".main").attr('value');

                if(vv >=start){

                    start = X>start ? start : X;

                    $(this).parent(".main").css({
                    '-webkit-transform':'translateX('+start+'px)'
                    }).attr('value',start);         
                }else{
                $(this).parent(".main").css({
                    '-webkit-transform':'translateX('+X+'px)'
                    }).attr('value',X);
                }

                if($(this).closest('.ruler').hasClass("ruler-weight")){
                    var val = (number-20+Math.abs(vv/g)/0.4).toFixed(1);//.replace('.0','');
                    $(this).closest(".row").find('.number').text(val);
                }else{
                    $(this).closest(".row").find('.number').text(Math.ceil(number-(vv/g)-10));

                    if($(this).closest('.ruler').hasClass("ruler-age")){
                        var ageVal = $(this).closest(".row").find('.number').text();
                        $(this).closest(".row").find('.number').text(parseInt(ageVal-2))
                    }
                }

            }else{

                var vv = $(this).parent(".main").attr('value');

                if($(this).parent(".main").attr('value') <=end){
                    end = X< end ? end : X;
                    $(this).parent(".main").css({
                    '-webkit-transform':'translateX('+end+'px)'
                    }).attr('value',end);
                }else{
                $(this).parent(".main").css({
                    '-webkit-transform':'translateX('+X+'px)'
                    }).attr('value',X);
                }

                if($(this).closest('.ruler').hasClass("ruler-weight")){

                var val = (number-20+Math.abs(vv/g)/0.4).toFixed(1);

                    if(val == '100.1'){val=100;}

                    $(this).closest(".row").find('.number').text(val);

                }else{
                    $(this).closest(".row").find('.number').text(Math.ceil(number+Math.abs(vv/g)-10));

                    if($(this).closest('.ruler').hasClass("ruler-age")){
                        var ageVal = $(this).closest(".row").find('.number').text();
                        $(this).closest(".row").find('.number').text(parseInt(ageVal-2))
                    }
                }
            }
            e.preventDefault();
        });


        $('.ruler ul').on("touchend",function(e){

            e.stopPropagation();

            moveEndX = e.originalEvent.changedTouches[0].screenX;

            X = moveEndX - startX;

            var arr = new Array();

            if($(this).closest('.ruler').hasClass("ruler-age")){

                var value=  Math.abs($(this).parent(".main").attr("value"));

                var value2 = Math.round(Math.abs(value)/100)*100;       

                if(value > value2){
                    value2+=50;
                }

                $(this).parent(".main").css({
                    '-webkit-transform':'translateX(-'+value2+'px)'
                    }).attr('value','-'+value2);
                }


                $(this).closest(".page").find(".number").each(function(){
                    var txt = $(this).text();
                    arr.push(txt);
                });

                var arrayJoin = arr.join('##');

                $(this).closest(".page").find('input[type="hidden"]').val(arrayJoin);

        });

    },100);

    $(".area-inputMain").click(function(){
        if($(".gearArea").length == 0){
            $(".overlayout").remove();
        }else{
            $(".overlayout").remove();
        }
    });

    // 
    $('div[data-page="profile7"] .row .selectize').click(function(){
        if($('div[data-page="profile7"] .row').eq(2).find(".val").text() == 0) {
            $('div[data-page="profile7"]').find(".page-bot a").attr("href", "#profile9");
        }
    });


    // 头部悬浮下载
    $(".download-close").click(function() {
        $(".download-box").attr("style", "display:none;");
    });
    

    // 输入手机号
    $('#tel-phone').click(function(){
        $("#tel-phone").attr("href", "javascript:;");
        if($(this).hasClass("btn-red")){
            $('.tel-box').addClass("rest-box-show").attr("style", "display:block;");
            if($('.overlayout').length ==0){
                $('body').append("<div class='overlayout'></div>")
            }
        }
    });

    $('.tel-box .tel-box-close').click(function(){
        $('.tel-box').removeClass("rest-box-show").removeAttr("style");
        $('.overlayout').remove();
    });

    $(".receive-btn").click(function(){
        var coded = $(".code-enter").val();
        var phone = $(".phone-enter").val();
        if (phone == ""){
            layer.msg('手机号码不能为空');
        }else if(!(/^1[34578]\d{9}$/.test(phone))){
            layer.msg('手机号码有误，请重填');
        }else if(coded !== ""){
            $.ajax({
                type: "post",
                url: "http://51son.net:8080/api/member/validationCode",
                data:{
                    mobile: $(".phone-enter").val(),
                    code: $(".code-enter").val(),
                    type: 1
                },
                success:function(result){
                    layer.msg(result.message);
                    if(result.success == true){
                        var token = result.data.token;
                        $(".tel-box").attr("data-id", "token");
                        $(".receive-btn").text("领取成功！").attr('disabled',true).addClass("active");
                        $('.tel-box').removeClass("rest-box-show").removeAttr("style");
                        $('.overlayout').remove();

                        window.location.href = '//'+host+'/webRoot/Html5/tools.html'+UrlFrom+'#profile10';

                        // 提交答题
                        layer.load(2);
                        $('body').append("<div class='overlayout'></div>");

                        var P1info = $('div[data-page="profile1"] input[name="first_screen"]').val().split('##');
                        var P7info = $('div[data-page="profile7"] input[name="seventh_screen"]').val().split('##');
                        var P8info = $('div[data-page="profile8"] input[name="eighth_screen"]').val().split('##');
                        var P9info = $('div[data-page="profile9"] input[name="ninth_screen"]').val().split('##');

                        var money = $("#budget-money").find(".selected").attr("data-key");

                        var toolsobj = {};
                        toolsobj.info = {
                            age: P1info[0],
                            height: P1info[1],
                            weight: P1info[2]
                        };
                        toolsobj.babyInfo = {
                            pregnancyCount: P7info[0],
                            babyCount: P7info[1],
                            tubeCount: P7info[2]
                        };
                        toolsobj.tubeInfo = {
                            tube_type: P8info[0],
                            tube_plan: P8info[1]
                        };
                        toolsobj.memberInfo = {
                            yourCity: $("#demo1").val(),
                            intentTo: P9info[1],
                            wishCity: $("#demo2").val(),
                            budget: money
                        };
                        var multi_select = [];
                        var p1 = {
                            title: "准爸爸妈妈面临哪些备孕难题？",
                            sort: 1,
                            options: [$('div[data-page="profile2"] input[name="second_screen"]').val()],
                        };
                        var p2 = {
                            title: "准爸爸精子情况如何？",
                            sort: 2,
                            options: [$('div[data-page="profile3"] input[name="third_screen"]').val()],
                        };
                        var p3 = {
                            title: "准妈妈卵巢请情况如何",
                            sort: 3,
                            options: [$('div[data-page="profile4"] input[name="fourth_screen"]').val()],
                        };
                        var p4 = {
                            title: "准妈妈输卵管情况如何",
                            sort: 4,
                            options: [$('div[data-page="profile5"] input[name="fifth_screen"]').val()],
                        };
                        var p5 = {
                            title: "准妈妈子宫情况如何",
                            sort: 5,
                            options: [$('div[data-page="profile6"] input[name="sixth_screen"]').val()],
                        };
                        multi_select.push(p1,p2,p3,p4,p5);
                        toolsobj.multi_select = multi_select;

                        setTimeout(function(){
                          $.ajax({
                                type: "post",
                                url: "http://51son.net:8080/api/testtools/testResults",
                                data: {
                                    token: token,
                                    info: JSON.stringify(toolsobj.info),
                                    multi_select: JSON.stringify(toolsobj.multi_select),
                                    babyInfo: JSON.stringify(toolsobj.babyInfo),
                                    tubeInfo: JSON.stringify(toolsobj.tubeInfo),
                                    memberInfo: JSON.stringify(toolsobj.memberInfo)
                                },
                                success:function(result){
                                    layer.closeAll('loading');
                                    $(".overlayout").remove();
                                    window.location.href = '//'+host+'/webRoot/Html5/tools.html'+UrlFrom+'#profile11';
                                    console.log(result);

                                    var succrate = result.data.score;
                                    var cycle = result.data.cycle;
                                    var cost = result.data.cost;
                                    var analysis = result.data.analysis;
                                    var suggest = result.data.advice;
                                    var cycless = cycle.split('-');
                                    var costss = cost.split('-');
                                    $('div[data-page="profile11"]').find('.info dl').eq(0).find("dd span").eq(0).text(cycless[0]);
                                    $('div[data-page="profile11"]').find('.info dl').eq(0).find("dd span").eq(1).text(cycless[1]);
                                    $('div[data-page="profile11"]').find('.info dl').eq(1).find("dd span").eq(0).text(costss[0]);
                                    $('div[data-page="profile11"]').find('.info dl').eq(1).find("dd span").eq(1).text(costss[1]);
                                    $('div[data-page="profile11"]').find('.analysis p').html(analysis);
                                    if(suggest == null) {
                                        $('div[data-page="profile11"]').find(".brick").attr("style", "display:none;");
                                    }else{
                                        $('div[data-page="profile11"]').find(".brick").attr("style", "display:block;");
                                        $('div[data-page="profile11"]').find('.brick p').html(suggest);
                                    };
                                    

                                    var my_canvas_obj= document.getElementById("my-canvas");
                                    var gauge= new SOFAGauge({
                                            "tick_length": 11, // 短刻度长度
                                            "large_tick_length": 11, // 长刻度长度
                                            "tick_thickness": 6, //刻度条宽度
                                            "tick_group_length": 8, //每组内的短刻度个数
                                            "ticks_groups_begin": 0, //起始点
                                            "total_degrees": 268, // 刻度的总角度
                                            "total_tick": 101,  // 刻度总个数
                                            "tick_color": "#eee", // 未达到的刻度颜色
                                            "tick_on_color": "#e87450", // 已达到的刻度颜色
                                            "bg_image": null,
                                            "center_font_size": 40,
                                            "animation_duration": 1000, //达到目标值的动画时间
                                            "percent": 0, // 起始百分比
                                            "gauge_scale": 0.95,
                                            "center_offset": -10,
                                            "canvas": my_canvas_obj // canvas元素
                                    });
                                    gauge.render(); //render the configured gauge
                                    gauge.updatePercent(succrate);
                                },
                                error:function(){
                                    layer.msg('网络连接异常，请稍后再试');
                                }
                          });
                        }, 1500);
                        
                        // 提交答题结束
                    }
                },
                error:function(){
                    layer.msg('请输入正确验证码');
                }
            });
        }else{
            layer.msg('请输入验证码');
        }
    });
    
};


    



// 
